package logic

import (
	"context"
	"reflect"

	"googee/common/utils"
	"googee/service/account/rpc/internal/svc"
	"googee/service/account/rpc/types/account"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type TransOutCancelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTransOutCancelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TransOutCancelLogic {
	return &TransOutCancelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 转出取消
func (l *TransOutCancelLogic) TransOutCancel(in *account.TransOutRequest) (*account.Empty, error) {
	configValue := reflect.ValueOf(l.svcCtx.Config.Digital)
	precision := configValue.FieldByName(utils.FirstUpper(in.GetField())).Uint()

	err := l.svcCtx.SqlConn.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		accountlog, err := l.svcCtx.AccountLogModel.FindOneByTransIdDir(l.ctx, in.TransId, 1)
		if err == sqlx.ErrNotFound {
			return nil
		}

		if accountlog.Status == 1 {
			return nil
		}

		err = l.svcCtx.AccountModel.AdjustTrading(l.ctx, in.Id, in.Field, in.Amount, uint8(precision))
		if err != nil {
			return err
		}

		accountlog.Status = -1
		err = l.svcCtx.AccountLogModel.Update(l.ctx, accountlog)
		if err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &account.Empty{}, nil
}
